package com.auditlog.boot.aop;

import com.auditlog.boot.annotations.AuditLog;
import com.auditlog.datasource.context.ContextHolder;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;

/**
 *
 * @author Zhiyang.Zhang
 * @date 2022/12/4 21:41
 * @version 1.0
 */
@Aspect
@AllArgsConstructor
@Order(0)
public class AuditLogAspect {

    @Around("@annotation(auditLog)")
    @SneakyThrows
    public Object around(ProceedingJoinPoint joinPoint, AuditLog auditLog) throws Throwable {
        try {
            Signature signature = joinPoint.getSignature();
            if (!(signature instanceof MethodSignature)) {
                return joinPoint.proceed();
            }
            LogContextHolder.get().setAudit(true);
            LogContextHolder.get().setOnExceptionContinue(auditLog.onExceptionContinue());
            ContextHolder.getConnectionContext().setOnExceptionContinue(auditLog.onExceptionContinue());
            ContextHolder.getExecuteContext().setOperationName(auditLog.operationName());
            ContextHolder.getExecuteContext().setAudit(true);
            Object result = joinPoint.proceed();
            return result;
        } finally {
            LogContextHolder.clear();
        }
    }

}
